<?php

class Core_Model_Foundation_Catalogue extends Dcmp_Model_Entity {

    public function __construct() {
        parent::__construct();
    }

    protected function getTableClass() {
        return Kd_Loader::loadClass('table_foundation_catalogue');
    }

    protected function beforeInsert($transaction){
        $parentCodes = $this->getParentCodes();
        if (is_null($parentCodes) || count($parentCodes) == 0) {
            $this->setParentCodes(array('00000000'));
        }
    }

    protected function insertSelf($transaction) {
        $data = $this->getAllData();
        if (array_key_exists('parent_codes', $data) && is_array($data['parent_codes'])) {
            $data['parent_codes'] = implode(',', array_unique($data['parent_codes']));
        }
        $this->getTable()->insert($data, $transaction);
        $this->setIdValue($this->getTable()->getInsertId($transaction));
    }

    public function afterInsert($transaction) {
        $parentCodes = $this->getParentCodes();
        $parents = array();
        if($parentCodes[0] == '00000000'){
            $parents[] = array('parentCode' =>'00000000','codePath' => $this->getCode() . '_');
        }else{
            $relations = $this->getTable()->getRelations(array_unique($parentCodes));
            foreach ($relations as $relation) {
                $parents[] = array(
                    'parentCode' => $relation['catalogue_code'],
                    'codePath' => $relation['code_path'] . $this->getCode() . '_'
                );
            }
        }
        $this->getTable()->insertRelation($this->getCode(), $parents, $transaction);
    }

    public function afterUpdate($transaction) {
        $this->getTable()->deleteRelation($this->getCode());
        $this->afterInsert($transaction);
    }

    public function fill($data) {
        if ($this->issetData('parent_codes') && !$this->isArrayData('parent_codes')) {
            $data['parent_codes'] = explode(',', $this->getParentCodes());
        }
        return parent::fill($data);
    }

    protected function initializeTable($table) {
        $table->setName('{t}foundation_catalogue');
        $table->createColumn('id', 'integer', TRUE, TRUE);
        $table->createColumn('code', 'string');
        $table->createColumn('name', 'string');
        $table->createColumn('parent_codes', 'string');
    }

}